package com.seecoder.BlueWhale.aspect;

import com.seecoder.BlueWhale.annotation.RoleAccessCheck;
import com.seecoder.BlueWhale.enums.RoleEnum;
import com.seecoder.BlueWhale.exception.BlueWhaleException;
import com.seecoder.BlueWhale.po.User;
import com.seecoder.BlueWhale.util.SecurityUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class RoleAccessCheckAspect {
    @Autowired
    SecurityUtil securityUtil;
    @Before("@annotation(roleAccessCheck)")
    public void accessCheck(JoinPoint joinPoint, RoleAccessCheck roleAccessCheck){
        switch (roleAccessCheck.role()) {
            case CUSTOMER:
                customerAccessCheck();
                break;
            case STAFF:
                stuffAccessCheck();
                break;
            case MANAGER:
                managerAccessCheck();
                break;
            case CEO:
                ceoAccessCheck();
                break;
        }
    }

    private void customerAccessCheck() {
        User user = securityUtil.getCurrentUser();
        if (user.getRole() != RoleEnum.CUSTOMER) {
            throw BlueWhaleException.customerAccessCheckFail();
        }
    }
    private void stuffAccessCheck() {
        User user = securityUtil.getCurrentUser();
        if (user.getRole() != RoleEnum.STAFF || user.getStoreId() == null) {
            throw BlueWhaleException.stuffAccessCheckFail();
        }
    }

    public void managerAccessCheck() {
        RoleEnum role = securityUtil.getCurrentUser().getRole();
        if (role != RoleEnum.MANAGER) {
            throw BlueWhaleException.managerAccessCheckFail();
        }
    }

    public void ceoAccessCheck() {
        RoleEnum role = securityUtil.getCurrentUser().getRole();
        if (role != RoleEnum.CEO) {
            throw BlueWhaleException.ceoAccessCheckFail();
        }
    }
}
